package com.sqfw.project.wp.publish;

import com.sqfw.common.utils.StringUtils;
import com.sqfw.project.wp.constant.WpState;
import com.sqfw.project.wp.domain.WpInfoReceive;
import com.sqfw.project.wp.domain.WpReceiveLog;

import com.sqfw.project.wp.mapper.WpInfoReceiveMapper;
import com.sqfw.project.wp.mapper.WpReceiveLogMapper;
import com.sqfw.project.wp.utils.FtpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;



@AutoPublishWS(publishPath = "thirdwebService")
@WebService
@Service
@Slf4j
public class ThirdwebServiceImpl implements ThirdwebService {


    private static final String FTP_HOST = "192.168.18.62";

    private static final Integer FTP_PORT = 21;

    private static final String FTP_USERNAME = "tangxt";

    private static final String FTP_PASSWORD = "tangxiaotao1994";

    @Autowired
    private WpReceiveLogMapper wpReceiveLogMapper;

    @Autowired
    private WpInfoReceiveMapper wpInfoReceiveMapper;


    @WebMethod
    @WebResult(name = "infoXML")
    @Override
    public String getInfo(@WebParam(mode = WebParam.Mode.IN, name = "info") String info) throws Exception {

        log.info("获取12345工单数据：{}",info);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //状态
        String STATUS = WpState.SUSS;
        //返回信息
        String MESSAGE = WpState.wpState(WpState.SUSS);

        Date date = new Date();
        //将XML数据转化为JSON
        JSONObject jsonObject  = XML.toJSONObject(info);

        JSONObject objectJSONObject = jsonObject.getJSONObject("Request");
        //获取参数
        JSONArray jsonArray = objectJSONObject.getJSONArray("param");

        WpInfoReceive wpInfoReceive = new WpInfoReceive();
        //循环jsonArray拿取数据
        try {
            jsonArray.forEach(obj -> {
                String s = obj.toString();
                //转化为实体类取值
                RequestVO requestVO = com.alibaba.fastjson2.JSONObject.parseObject(s, RequestVO.class);
                String content = requestVO.getContent();
                if (content != null) {
                    String requestVOName = requestVO.getName();
                    //12345工单编号
                    switch (requestVOName) {
                        case "WPID":
                            wpInfoReceive.setTsWpid(content);
                            break;
                        case "SUMMARY":
                            wpInfoReceive.setSummary(content);
                            break;
                        case "TIME_BOUNDRY":
                            //截止时间
                            //wpInfoReceive.setTimeBoundry(content);
                            break;
                        case "PRIORITY":
                            //工单优先级标示：
                            // 0：紧急
                            //1：普通
                            //2：次紧急
                            //本库使用wpLevel字段
                            String priority = "";
                            if ("0".equals(content)) {
                                priority = "0";
                            }else if ("2".equals(content)) {
                                priority = "1";
                            }
                            wpInfoReceive.setPriority(priority);
                            break;
                        case "REL_NAME":
                            //姓名
                            wpInfoReceive.setRelName(content);
                            wpInfoReceive.setCustomerName(content);
                            break;
                        case "SUPERVISION":
                            //工单类型标示：
                            // 0：转送单
                            //1：为督办单
                            wpInfoReceive.setSupervision(content);
                            break;
                        case "SEND_TIME":
                            //分配时间
                            Date parse = null;
                            try {
                                parse = simpleDateFormat.parse(content);
                            } catch (ParseException e) {
                                log.info("SEND_TIME时间转换异常");
                                e.printStackTrace();
                            }
                            wpInfoReceive.setStarttime(parse);
                            break;
                        case "NOTE":
                            //
                            wpInfoReceive.setNote(content);
                            break;
                        case "CALLNUM": // 12345传递的是联系方式，
                            // mobile
                            wpInfoReceive.setMobile(content);
                            break;
                        case "START_TIME":
                            //派单时间  TODO 暂时该字段未使用
                            break;
                        case "REL_PHONENO":
                            //电话
                            wpInfoReceive.setPhoneno(content);
                            wpInfoReceive.setRelPhoneno(content);
                            break;
                        case "WP_SOURCE":
                            //工单来源
                            wpInfoReceive.setWpSource(content);
                            break;
                        case "CLASS4":
                            //内容分类4
                            wpInfoReceive.setClass4(content);
                            break;
                        case "MESSAGE":
                            //处理信息
                            wpInfoReceive.setLastmessage(content);
                            break;
                        case "CLASS1":
                            //内容分类1
                            wpInfoReceive.setClass1(content);
                            break;
                        case "REL_DISTRICT":
                            //地区
                            /*wpInfoReceive.setRelDistrict(content);
                            wpInfoReceive.setDistrict(content);*/
                            break;
                        case "CLASS2":
                            //内容分类2
                            wpInfoReceive.setClass2(content);
                            break;
                        case "CLASS3":
                            //内容分类3
                            wpInfoReceive.setClass3(content);
                            break;
                        case "WP_TYPE":
                            //来电类别
                            wpInfoReceive.setWpType(content);
                            break;
                        case "REL_ADDRESS":
                            //地址
                            wpInfoReceive.setRelAddress(content);
                            wpInfoReceive.setAddress(content);
                            break;
                        case "APPEAL_UPLOAD":
                            //12345工单系统附件
                            wpInfoReceive.setAppealUpload(content);
                            break;
                        case "CARDNUM":
                            //身份证字段换成callnum
                            wpInfoReceive.setCallnum(content);
                            break;
                        case "NEW_CLASS1":
                            // NEW_CLASS1--新行业分类1级
                            wpInfoReceive.setNewClass1(content);
                            break;
                        case "NEW_CLASS2":
                            // NEW_CLASS2---新行业分类2级
                            wpInfoReceive.setNewClass2(content);
                            break;
                        case "NEW_CLASS3":
                            // NEW_CLASS3---新行业分类3级
                            wpInfoReceive.setNewClass3(content);
                            break;
                        case "NEW_CLASS4":
                            // NEW_CLASS4---新行业分类4级
                            wpInfoReceive.setNewClass4(content);
                            break;
                        case "NEW_CLASS5":
                            // NEW_CLASS5---新行业分类5级
                            wpInfoReceive.setNewClass5(content);
                            break;
                    }
                }
            });
        } catch (Exception e) {
            log.info("jsonArray循环异常");
            e.printStackTrace();
        }


        wpInfoReceive.setScidType("12345工单");
        wpInfoReceive.setState("12345接收");
        wpInfoReceive.setNextState("社区接收");
        //代表该12345工单待分配
        wpInfoReceive.setStatus("0");
        //创建时间
        wpInfoReceive.setTimestamp(date);

        if (StringUtils.isEmpty(wpInfoReceive.getScidType())){
            STATUS = WpState.ERROR3;
            MESSAGE = WpState.wpState(WpState.ERROR3);
        }

        List<WpInfoReceive> wpInfoReceives =  wpInfoReceiveMapper.selectWpInfoReceiveByTsWpid(wpInfoReceive.getTsWpid());
        if (wpInfoReceives.size()>0){
            WpReceiveLog wpReceiveLog = new WpReceiveLog();
            wpReceiveLog.setCreateTime(date);
            wpReceiveLog.setType("12345工单推送");
            wpReceiveLog.setContent(info);
            //插入12345推送记录
            wpReceiveLogMapper.insertWpReceiveLog(wpReceiveLog);

            WpReceiveLog wpReceiveLogCon = new WpReceiveLog();
            wpReceiveLogCon.setCreateTime(new Date());
            wpReceiveLogCon.setType("反馈12345收单");

            STATUS = WpState.ERROR6;
            MESSAGE = WpState.wpState(WpState.ERROR6);

            String infoXML = "<?xml version='1.0' encoding='UTF-8'?>" +
                    "<Response>" +
                    "<param name='WPID'>" + wpInfoReceive.getTsWpid() + "</param>" +
                    "<param name='STATUS'>" + STATUS + "</param>" +
                    "<param name='MESSAGE'>" + MESSAGE + "</param>" +
                    "</Response>";
            wpReceiveLogCon.setContent(infoXML);
            //插入12345推送记录
            wpReceiveLogMapper.insertWpReceiveLog(wpReceiveLogCon);
            return infoXML;
        }
        //插入12345工单接收表
        wpInfoReceiveMapper.insertWpInfoReceive(wpInfoReceive);
        WpReceiveLog wpReceiveLog = new WpReceiveLog();
        wpReceiveLog.setCreateTime(date);
        wpReceiveLog.setType("12345工单推送");
        wpReceiveLog.setContent(info);
        //插入12345推送记录
        wpReceiveLogMapper.insertWpReceiveLog(wpReceiveLog);

        WpReceiveLog wpReceiveLogCon = new WpReceiveLog();
        wpReceiveLogCon.setCreateTime(new Date());
        wpReceiveLogCon.setType("反馈12345收单");


        String infoXML = "<?xml version='1.0' encoding='UTF-8'?>" +
                "<Response>" +
                "<param name='WPID'>" + wpInfoReceive.getTsWpid() + "</param>" +
                "<param name='STATUS'>" + STATUS + "</param>" +
                "<param name='MESSAGE'>" + MESSAGE + "</param>" +
                "</Response>";
        wpReceiveLogCon.setContent(infoXML);
        //插入12345推送记录
        wpReceiveLogMapper.insertWpReceiveLog(wpReceiveLogCon);
        return infoXML;
    }

    /**
     *
     * @param path  FTP储存文件相对路径
     * @param fileName  下载到指定路径+文件名称  可以拆分成两个参数
     * @throws Exception
     */
    public void downFileByFTP(String path,String fileName) throws Exception{

        FTPClient ftpClient = FtpUtil.getFtpClient(FTP_HOST, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);

        // 展示文件夹
        /*FTPFile[] ftpFiles = ftpClient.listDirectories();
        for(FTPFile file : ftpFiles){
            System.out.println(file.getName());
        }*/

        // 下载文件   path   fileName
        FtpUtil.download(ftpClient, "20230706/1688614322138.jpg", "D:\\test\\123456.jpg");

        // 上传文件
        //   FtpUtil.upload(ftpClient, "D:\\test\\test.py");


        FtpUtil.disConnect(ftpClient);

    }
}

